package com.example.common.util;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 雪花算法
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/4
 */
public class SnowFlakeUtils {

    // 起始时间戳（2023-01-01）
    private static final long START_TIMESTAMP = 1672502400000L;

    // 机器ID所占位数
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID所占位数
    private static final long DATACENTER_ID_BITS = 5L;
    // 序列号所占位数
    private static final long SEQUENCE_BITS = 12L;

    // 最大机器ID (2^5-1)
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 最大数据中心ID (2^5-1)
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);

    // 机器ID左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 数据中心ID左移位数
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 时间戳左移位数
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    // 序列号掩码 (2^12-1)
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    // 数据中心ID (0-31)
    private final long datacenterId;
    // 机器ID (0-31)
    private final long workerId;
    // 序列号 (0-4095)
    private final AtomicLong sequence = new AtomicLong(0L);
    // 上次生成ID的时间戳
    private volatile long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param datacenterId 数据中心ID (0-31)
     * @param workerId 机器ID (0-31)
     */
    public SnowFlakeUtils(long datacenterId, long workerId) {
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenterId can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("workerId can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        this.datacenterId = datacenterId;
        this.workerId = workerId;
    }

    /**
     * 生成下一个ID
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        // 如果当前时间小于上次ID生成的时间戳，说明系统时钟回退过
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }

        // 如果是同一时间生成的，则进行序列号自增
        if (lastTimestamp == timestamp) {
            long sequenceVal = sequence.incrementAndGet() & SEQUENCE_MASK;
            // 序列号溢出，等待下一个毫秒
            if (sequenceVal == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，序列号重置
            sequence.set(0L);
        }

        lastTimestamp = timestamp;

        // 拼接各部分数据
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence.get();
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回当前时间戳
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }

    // 单例模式（默认数据中心ID为0，机器ID为0）
    private static final SnowFlakeUtils INSTANCE = new SnowFlakeUtils(0, 0);

    /**
     * 获取默认的SnowFlake实例
     */
    public static SnowFlakeUtils getInstance() {
        return INSTANCE;
    }

    /**
     * 生成下一个ID（使用默认实例）
     */
    public static long generateId() {
        return INSTANCE.nextId();
    }
}